import React, { useState } from 'react';
import { Modal, Form, Button, Input, ConfigProvider, message } from 'antd';
import { createSegment } from '@/services/project';
import eventBus from '@/utils/eventBus';

interface AddTextClipModalProps {
    visible: boolean;
    trackId: string;
    draftId: string;
    renderIndex: number;
    onCancel: () => void;
}

const DEFAULT_SEGMENT_CONFIG = {
    styles: [
        {
            fill: {
                alpha: 1.0,
                content: {
                    render_type: 'solid',
                    solid: {
                        alpha: 1.0,
                        color: [1.0, 1.0, 1.0], // 白色
                    },
                },
            },
            range: [0, 11],
            size: 12.0,
            bold: false,
            italic: false,
            underline: false,
            strokes: [
                {
                    width: 0, // 宽度为 0
                    content: {
                        solid: {
                            alpha: 1.0,
                            color: [1.0, 1.0, 1.0], // 白色描边
                        },
                    },
                },
            ],
        },
    ],
};
const darkThemeStyles = {
    card: {
        backgroundColor: '#1f1f1f',
        borderColor: '#303030',
    },
    text: {
        primary: '#ffffff',
        secondary: 'rgba(255, 255, 255, 0.65)',
    },
};

const AddTextClipModal: React.FC<AddTextClipModalProps> = ({ visible, trackId, draftId, renderIndex, onCancel }) => {
    const [form] = Form.useForm();
    const [submitting, setSubmitting] = useState(false);

    const handleSubmit = async () => {
        try {
            // 验证表单
            const values = await form.validateFields();

            // 检查是否输入了文字内容
            if (!values.segment_config.text || values.segment_config.text.trim() === '') {
                message.error('请输入文字内容');
                return;
            }

            setSubmitting(true);

            // 创建文字片段数据，使用默认配置和默认时间
            const segmentData = {
                type: 'text',
                start: 0, // 默认开始时间为 0
                duration: 5000000, // 默认持续时间为 5 秒 (5,000,000 微秒)
                render_index: renderIndex,
                segment_config: {
                    text: values.segment_config.text.trim(),
                    ...DEFAULT_SEGMENT_CONFIG,
                },
            };
            // 调用创建片段接口
            createSegment(draftId, trackId, segmentData)
                .then(() => {
                    message.success('文字片段添加成功'); 
                    // 触发事件总线通知更新
                    eventBus.emit('track:added', {
                        trackType: 'text',
                        trackId,
                    });
                    // 触发片段配置更新事件，通知 VideoPreview 重新渲染
                    eventBus.emit('segmentConfig:updated', {
                        draftId,
                        trackId,
                        segmentId: 'new', // 新创建的片段
                        config: segmentData.segment_config
                    });
                    // 重置表单并关闭模态框
                    form.resetFields();
                    onCancel();
                })
                .catch(() => {
                    message.error('文字片段创建失败，请重试');
                })
                .finally(() => {
                    setSubmitting(false);
                });
        } catch (error) {
            message.error('请检查表单填写是否正确');
            setSubmitting(false);
        }
    };

    const handleCancel = () => {
        form.resetFields();
        // 调用父组件传递的onCancel函数关闭模态框
        onCancel();
    };

    return (
        <Modal
            title="添加文字片段"
            open={visible}
            onCancel={submitting ? undefined : handleCancel}
            destroyOnHidden
            footer={null}
            zIndex={9999}
            width={600}
            centered
            closable={!submitting}
            maskClosable={!submitting}
            styles={{
                header: {
                    background: darkThemeStyles.card.backgroundColor,
                    borderBottom: `1px solid ${darkThemeStyles.card.borderColor}`,
                },
                body: {
                    background: darkThemeStyles.card.backgroundColor,
                },
                footer: {
                    background: darkThemeStyles.card.backgroundColor,
                    borderTop: `1px solid ${darkThemeStyles.card.borderColor}`,
                },
                mask: {
                    backdropFilter: 'blur(4px)',
                },
                content: {
                    background: darkThemeStyles.card.backgroundColor,
                    boxShadow: '0 4px 12px rgba(0, 0, 0, 0.5)',
                },
            }}
            className="dark-theme-modal"
        >
            <ConfigProvider
                theme={{
                    components: {
                        Form: {
                            labelColor: darkThemeStyles.text.primary,
                            colorText: darkThemeStyles.text.primary,
                        },
                        InputNumber: {
                            colorBgContainer: '#2a2a2a',
                            colorBorder: '#434343',
                            colorText: darkThemeStyles.text.primary,
                        },
                        Input: {
                            colorBgContainer: '#2a2a2a',
                            colorBorder: '#434343',
                            colorText: darkThemeStyles.text.primary,
                        },
                        Button: {
                            colorBgContainer: '#2a2a2a',
                            colorBorder: '#434343',
                            colorText: darkThemeStyles.text.primary,
                        },
                    },
                }}
            >
                <Form
                    form={form}
                    layout="vertical"
                    initialValues={{
                        segment_config: {
                            text: '',
                        },
                    }}
                >
                    {/* 文字内容 */}
                    <div
                        style={{
                            marginBottom: 16,
                            color: darkThemeStyles.text.primary,
                            fontSize: '16px',
                            fontWeight: 500,
                        }}
                    >
                        文字内容
                    </div>

                    <Form.Item
                        label="文字内容"
                        name={['segment_config', 'text']}
                        rules={[
                            { required: true, message: '请输入文字内容' },
                            { whitespace: true, message: '文字内容不能为空' },
                        ]}
                    >
                        <Input.TextArea
                            rows={4}
                            placeholder="请输入要显示的文字内容..."
                            maxLength={500}
                            showCount
                            style={{
                                backgroundColor: '#2a2a2a',
                                borderColor: '#434343',
                                color: darkThemeStyles.text.primary,
                            }}
                        />
                    </Form.Item>
                </Form>

                {/* 自定义底部按钮区域 */}
                <div
                    style={{
                        marginTop: '32px',
                        paddingTop: '16px',
                        borderTop: `1px solid ${darkThemeStyles.card.borderColor}`,
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                    }}
                >
                    <Button
                        onClick={handleCancel}
                        disabled={submitting}
                        style={{
                            backgroundColor: '#2a2a2a',
                            borderColor: '#434343',
                            color: darkThemeStyles.text.primary,
                            opacity: submitting ? 0.5 : 1,
                        }}
                    >
                        取消
                    </Button>

                    <Button
                        type="primary"
                        onClick={handleSubmit}
                        loading={submitting}
                        disabled={submitting}
                        style={{
                            backgroundColor: '#1890ff',
                            borderColor: '#1890ff',
                            color: '#ffffff',
                        }}
                    >
                        {submitting ? '创建中...' : '确定'}
                    </Button>
                </div>
            </ConfigProvider>
        </Modal>
    );
};

export default AddTextClipModal;
